/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wap.rockvilletech.portal;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import wap.rockvilletech.util.StringUtils;
import wap.rockvilletech.xms.SendXMSManager;

/**
 *
 * @author M Bilal
 */
@SuppressWarnings("serial")
public class ChargingOnMOServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(ChargingOnMOServlet.class);

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String context = getServletContext().getContextPath();
        WapPortalBean wpb = new WapPortalBean();
        String wappushLink = "", resp = "";
        if (context.equalsIgnoreCase("/")) {
            context = "";
        }
        String contentId = request.getParameter("cntid") != null ? request.getParameter("cntid").trim() : "";
        String msisdn = request.getParameter("msisdn") != null ? request.getParameter("msisdn").trim() : "";
        String sc = request.getParameter("sc") != null ? request.getParameter("sc").trim() : "";
        try {
            log.info("Request Params, cntid=" + contentId + ", msisdn=" + msisdn + ", sc=" + sc);
            if (contentId.isEmpty() || msisdn.isEmpty() || sc.isEmpty()) {
                log.warn("UN-AUTHORIZED ACCESS TO DOWNLOAD CONTENT");
                printTextResponse(response, "UN-AUTHORIZED ACCESS TO DOWNLOAD CONTENT");
                return;
            }
            if ("6211".equals(sc)) {
            	try {
	                String strEncGSM = StringUtils.encryptString(msisdn, SystemProperty.getProperty("msisdn_encrypt_key"));
	                wappushLink = "http://wap.ufone.com/fileshare/?u="+strEncGSM;
	                resp = SendXMSManager.sendWAPPush(msisdn, SystemProperty.getProperty("smpp_provider"), sc, "Click Ufone UShare link below", wappushLink);
	                log.info("FileShare WAPPUSH link=" + wappushLink + " is sent to (" + msisdn + "), resp=" + resp);
	                printTextResponse(response, "SUCCESS");
            	} catch(Exception e) {            		
            		log.error("", e);
            		printTextResponse(response, "FAIL");
            	}
                return;
            }
            Pattern p = Pattern.compile("([cC][aA][rR][dD])([ ]*)([0-9]+)");
            Matcher m = p.matcher(contentId);
            if (m.matches() && m.groupCount() == 3) {//ugreetings card download request            	
                String cardId = m.group(3);
                log.info("UGreetings Card send Request, cardId=" + cardId);
                String port = wpb.getShortCodeOnPrice(10);
                if (!port.equals(sc)) {
                    String msg = "Shortcode not valid for the content, please send sms \"" + contentId + " to " + port + "\"";
//		        	resp = wpb.sendSMS(msisdn, msg);
                    resp = SendXMSManager.sendXMS(msisdn, msg, sc, SystemProperty.getProperty("smpp_provider"));
                    log.info("Invalid shortcode, port=" + port + ", shortcode=" + sc + " sendSMS resp=" + resp);
                    printTextResponse(response, "INVALID_SHORTCODE");
                    return;
                }
                UGreetingsBean ugb = new UGreetingsBean();
                String[] cardInfo = ugb.getGreetingCardInfo(cardId);
                //ContentId,CatID,CatName,Sender,Rcv_MSISDN
                if (cardInfo != null) {
                    String strContentID = cardInfo[0];
                    String strCatID = cardInfo[1];
                    String strCatName = cardInfo[2];
                    String strSndrName = cardInfo[3];
                    String strRecvGSM = cardInfo[4];

                    String wapText = "Click to download Greeting Card sent by " + strSndrName + ".";
//	                wappushLink = "http://wap.ufone.com"+context+"/ugreetings/ucdh%3Fsid%3D"+cardId;	                
//	                resp = wpb.sendWappush(strRecvGSM, wapText, wappushLink);
                    wappushLink = "http://wap.ufone.com" + context + "/ugreetings/ucdh?sid=" + cardId;
                    resp = SendXMSManager.sendWAPPush(strRecvGSM, SystemProperty.getProperty("smpp_provider"), sc, wapText, wappushLink);

                    int lastInsertId = wpb.persistContentCharging(contentId, strCatID, strCatName, request.getQueryString(), sc, msisdn);
                    ugb.updateGreetingCardSenderInfo(cardId, msisdn, lastInsertId, resp);

                    String msg = "";
                    if ("1".equals(resp)) {
                        msg = "UGreeting Card (" + strContentID + ") is sent successfully to " + strRecvGSM;
//	                	resp = wpb.sendSMS(msisdn, msg);
                        resp = SendXMSManager.sendXMS(msisdn, msg, sc, SystemProperty.getProperty("smpp_provider"));
                        log.info("SMS from (" + msisdn + ") " + msg + ", resp=" + resp);
                    } else {
                        msg = "Error processing your UGreeting Card (" + strContentID + ") send request, please try later!";
//	                	resp = wpb.sendSMS(msisdn, msg);
                        resp = SendXMSManager.sendXMS(msisdn, msg, sc, SystemProperty.getProperty("smpp_provider"));
                        log.info("SMS from (" + msisdn + ") " + msg + ", resp=" + resp);
                    }
                    printTextResponse(response, "SUCCESS");
                } else {
                    log.info("Invalid Card ID, cardID=" + cardId);
                    printTextResponse(response, "INVALID_CARD_ID");
                }
            } else {//wap portal content download request
                Vector v = wpb.getContentDetails(contentId);
                String price = "", contentType = "", categoryId = "";
                try {
                    Vector vin = (Vector) v.get(0);
                    price = String.valueOf((Long) vin.get(2));
                    contentType = (String) vin.get(3);
                    categoryId = String.valueOf((Long) vin.get(4));
                } catch (Exception ex) {
                    //	        	log.error("Error getting content("+contentId+") details; price="+price+", contentType="+contentType+", categoryId="+categoryId, ex);
                    price = "";
                    contentType = "";
                    categoryId = "";
                }
                String msg = "";
                if (price.isEmpty() || contentType.isEmpty() || categoryId.isEmpty()) {
                    msg = "Content ID not valid, please send correct id";
//		            resp = wpb.sendSMS(msisdn, msg);
                    resp = SendXMSManager.sendXMS(msisdn, msg, sc, SystemProperty.getProperty("smpp_provider"));
                    log.info("SMS from (" + msisdn + ") " + msg + ", resp=" + resp);
                    printTextResponse(response, "INVALID_CONTENT_ID");
                } else {
                    String port = wpb.getShortCodeOnPrice(Integer.parseInt(price));
                    if (!port.equals(sc)) {
                        msg = "Shortcode not valid for the content, please send sms \"" + contentId + " to " + port + "\"";
//			        	resp = wpb.sendSMS(msisdn, msg);
                        resp = SendXMSManager.sendXMS(msisdn, msg, sc, SystemProperty.getProperty("smpp_provider"));
                        log.info("SMS from (" + msisdn + ") " + msg + ", resp=" + resp);
                        printTextResponse(response, "INVALID_SHORTCODE");
                        return;
                    }
                    int lastInsertId = wpb.persistContentCharging(contentId, categoryId, contentType, request.getQueryString(), sc, msisdn);
                    wpb.saveDownload(contentId, msisdn, "", "", String.valueOf(lastInsertId), "UFONEWAP");
                    String downloadEntry = StringUtils.encryptString(String.valueOf(lastInsertId), SystemProperty.getProperty("msisdn_encrypt_key"));
//		            wappushLink = context+"/download.jsp%3Fentry%3D"+downloadEntry;
//		            resp = wpb.sendWappush(msisdn, "Click%20to%20Download", "http://wap.ufone.com"+wappushLink);
                    wappushLink = "http://wap.ufone.com" + context + "/download.jsp?entry=" + downloadEntry;
                    resp = SendXMSManager.sendWAPPush(msisdn, SystemProperty.getProperty("smpp_provider"), sc, "Click to Download", wappushLink);
                    log.info("WAPPUSH from (" + msisdn + ") is sent link=" + wappushLink + ", resp=" + resp);
                    printTextResponse(response, "SUCCESS");
                }
            }
        } catch (Exception e) {
            log.error("Error processing request (" + contentId + "," + msisdn + "," + sc + ")", e);
            printTextResponse(response, "FAIL");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * prints text response on servlet output stream
     * @param resp
     * @param text
     */
    private void printTextResponse(HttpServletResponse resp, String text) {
        try {
            resp.setContentType("text/plain");
            PrintWriter out = resp.getWriter();
            out.print(text);
            out.close();
        } catch (IOException e) {
            log.error("printTextResponse(" + text + ")", e);
        }
    }
}
